<template>
  <div v-if="getShow" class="modern-mobile-login-wrapper">
    <div class="modern-mobile-login-container">
      <div class="form-header">
        <h2>{{ t('sys.login.mobileLogin') }}</h2>
        <p>{{ t('sys.login.contactLoginDesc') }}</p>
      </div>

      <form @submit.prevent="handleLogin" class="floating-form" autocomplete="off">
        <!-- 隐藏假字段，防止自动填充 -->
        <input type="text" style="display: none" autocomplete="username" />
        <input type="password" style="display: none" autocomplete="new-password" />

        <div class="input-group">
          <input
            id="contact"
            v-model.trim="formData.contact"
            type="text"
            autocomplete="off"
            :name="'contact_' + Math.random().toString(36).slice(2)"
            @input="onContactInput"
            @focus="handleFocus"
            @blur="handleContactBlur"
            required
          />
          <label for="contact" :class="{ focused: formData.contact }">{{ t('sys.login.contact') }}</label>
        </div>

        <div class="input-group sms-input-group">
          <input
            id="sms"
            v-model.trim="formData.sms"
            type="text"
            autocomplete="off"
            :name="'sms_' + Math.random().toString(36).slice(2)"
            @input="validateInput"
            @focus="handleFocus"
            @blur="handleBlur"
            required
          />
          <label for="sms" :class="{ focused: formData.sms }">{{ t('sys.login.inputCode') }}</label>
          <button
            type="button"
            class="send-sms-btn"
            @click="handleSendSms"
            :disabled="!contactValidation?.isValid || smsLoading || countdown > 0"
            :class="{ loading: smsLoading }"
          >
            <span v-if="!smsLoading && !countdown">{{ t('sys.login.sendSms') }}</span>
            <span v-else-if="!smsLoading && countdown">{{ countdown }}s</span>
            <LoadingOutlined v-else class="loading-icon" />
          </button>
        </div>

        <div class="button-group">
          <button type="submit" class="submit-btn" :disabled="!isFormValid || loading" :class="{ loading: loading }">
            <span v-if="!loading">{{ t('sys.login.loginButton') }}</span>
            <span v-else>{{ t('sys.login.loggingIn') }}</span>
            <LoadingOutlined v-if="loading" class="loading-icon" />
          </button>
          <button type="button" class="back-btn" @click="handleBackLogin">
            {{ t('sys.login.backSignIn') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, unref, toRaw, onMounted, onBeforeUnmount } from 'vue';
  import { LoadingOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useLoginState, LoginStateEnum, SmsEnum } from './useLogin';
  import { useUserStore } from '/@/store/modules/user';
  import { getCaptcha, verifyCodeEmail } from '/@/api/sys/user';

  const { t } = useI18n();
  const { handleBackLogin, getLoginState } = useLoginState();
  const { notification } = useMessage();
  const userStore = useUserStore();

  // 控制组件显示
  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.MOBILE);

  // 表单数据
  const formData = reactive({
    contact: '',
    sms: '',
  });

  // 状态管理
  const isFormValid = ref(false);
  const isContactValid = ref(false);
  const contactValidation = ref<{ isValid: boolean; type: string | null; message: string; show: boolean } | null>(null);
  const loading = ref(false);
  const smsLoading = ref(false);
  const countdown = ref(0);
  let countdownTimer: NodeJS.Timeout | null = null;

  // 联系方式验证 - 智能判断
  const validateContact = (contact: string) => {
    // 判断是否为纯数字（手机号）
    const isAllNumbers = /^\d+$/.test(contact);
    // 判断是否包含@或字母（邮箱）
    const hasEmailChars = /[@a-zA-Z]/.test(contact);

    if (isAllNumbers) {
      // 纯数字按手机号验证
      const phonePattern = /^1[3-9]\d{9}$/;
      if (phonePattern.test(contact)) {
        return { isValid: true, type: 'phone', message: '手机号格式正确', show: false };
      } else {
        return { isValid: false, type: 'phone', message: '请输入有效的手机号（11位数字）', show: false };
      }
    } else if (hasEmailChars) {
      // 包含@或字母按邮箱验证
      const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (emailPattern.test(contact)) {
        return { isValid: true, type: 'email', message: '邮箱格式正确', show: false };
      } else {
        return { isValid: false, type: 'email', message: '请输入有效的邮箱地址', show: false };
      }
    } else {
      return { isValid: false, type: null, message: '请输入有效的手机号或邮箱地址', show: false };
    }
  };

  // 输入验证
  const validateInput = () => {
    const hasContact = formData.contact.trim().length > 0;
    const hasSms = formData.sms.trim().length > 0;
    isFormValid.value = hasContact && hasSms && isContactValid.value;
  };

  // 处理输入框焦点
  const handleFocus = (event) => {
    const input = event.target;
    const label = input.nextElementSibling;

    // 添加一些炫酷的初始效果
    label.style.transform = 'translateY(-50%) translateX(0) rotate(0deg) scale(1)';
    label.style.opacity = '1';

    // 添加轻微的弹跳效果
    setTimeout(() => {
      label.style.transform = 'translateY(-50%) translateX(0) rotate(0deg) scale(1.05)';
      setTimeout(() => {
        label.style.transform = 'translateY(-50%) translateX(0) rotate(0deg) scale(1)';
        label.classList.add('focused');
      }, 100);
    }, 50);
  };

  // 处理输入框失焦
  const handleBlur = (event) => {
    const input = event.target;
    const label = input.nextElementSibling;

    if (!input.value) {
      // 先设置初始状态（向右移出）
      label.style.transform = 'translateY(-50%) translateX(100px) rotate(15deg) scale(0.8)';
      label.style.opacity = '0';

      // 短暂延迟后播放向左移入动画
      setTimeout(() => {
        label.classList.remove('focused');
        label.style.animation = 'labelSlideIn 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards';

        // 动画结束后清除样式并添加弹跳效果
        setTimeout(() => {
          label.style.animation = '';
          label.style.transform = '';
          label.style.opacity = '';

          // 添加最终的弹跳效果
          setTimeout(() => {
            label.style.transform = 'translateY(-50%) translateX(0) rotate(0deg) scale(1.1)';
            setTimeout(() => {
              label.style.transform = 'translateY(-50%) translateX(0) rotate(0deg) scale(1)';
            }, 150);
          }, 50);
        }, 600);
      }, 50);
    }
  };

  // 实时校验联系方式
  const onContactInput = () => {
    contactValidation.value = validateContact(formData.contact);
    isContactValid.value = contactValidation.value.isValid;
    validateInput();
  };

  // 处理联系方式失焦
  const handleContactBlur = (event) => {
    const input = event.target;
    const label = input.nextElementSibling;

    if (!input.value) {
      // 先设置初始状态（向右移出）
      label.style.transform = 'translateY(-50%) translateX(100px) rotate(15deg) scale(0.8)';
      label.style.opacity = '0';

      // 短暂延迟后播放向左移入动画
      setTimeout(() => {
        label.classList.remove('focused');
        label.style.animation = 'labelSlideIn 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards';

        // 动画结束后清除样式并添加弹跳效果
        setTimeout(() => {
          label.style.animation = '';
          label.style.transform = '';
          label.style.opacity = '';

          // 添加最终的弹跳效果
          setTimeout(() => {
            label.style.transform = 'translateY(-50%) translateX(0) rotate(0deg) scale(1.1)';
            setTimeout(() => {
              label.style.transform = 'translateY(-50%) translateX(0) rotate(0deg) scale(1)';
            }, 150);
          }, 50);
        }, 600);
      }, 50);
    }
  };

  // 发送验证码
  const handleSendSms = async () => {
    if (!contactValidation.value?.isValid) {
      notification.error({
        message: t('sys.login.pleaseEnterContact'),
        duration: 3,
      });
      return;
    }

    if (smsLoading.value || countdown.value > 0) return;

    try {
      smsLoading.value = true;
      const contactType = contactValidation.value.type;

      if (contactType === 'email') {
        await verifyCodeEmail({
          email: formData.contact,
          model: '0',
          username: formData.contact,
        });
        notification.success({
          message: t('sys.login.emailCodeSent'),
          duration: 3,
        });
      } else if (contactType === 'phone') {
        await getCaptcha({
          mobile: formData.contact,
          smsmode: SmsEnum.FORGET_PASSWORD,
        });
        notification.success({
          message: t('sys.login.smsCodeSent'),
          duration: 3,
        });
      } else {
        notification.error({
          message: t('sys.login.contactTypeIncorrect'),
          duration: 3,
        });
        return;
      }

      // 开始倒计时
      countdown.value = 60;
      countdownTimer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(countdownTimer!);
          countdownTimer = null;
        }
      }, 1000);
    } catch (error: any) {
      notification.error({
        message: t('sys.api.errorTip'),
        description: error?.message || t('sys.api.networkExceptionMsg'),
        duration: 3,
      });
    } finally {
      smsLoading.value = false;
    }
  };

  // 登录处理
  const handleLogin = async () => {
    if (!isFormValid.value || loading.value) return;

    try {
      loading.value = true;
      const contactType = contactValidation.value?.type;

      // 根据联系方式类型构建登录参数
      const loginParams: any = {
        captcha: formData.sms,
        mode: 'none',
      };

      if (contactType === 'email') {
        loginParams.email = formData.contact;
      } else if (contactType === 'phone') {
        loginParams.mobile = formData.contact;
      }

      const userInfo = await userStore.phoneLogin(toRaw(loginParams));

      if (userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.userInfo.realname}`,
          duration: 3,
        });
      }
    } catch (error: any) {
      notification.error({
        message: t('sys.api.errorTip'),
        description: error?.message || t('sys.api.networkExceptionMsg'),
        duration: 3,
      });
    } finally {
      loading.value = false;
    }
  };

  // 初始化
  onMounted(() => {
    validateInput();
  });

  onBeforeUnmount(() => {
    if (countdownTimer) {
      clearInterval(countdownTimer);
    }
  });
</script>

<style scoped lang="less">
  .modern-mobile-login-wrapper {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
  }

  .modern-mobile-login-container {
    width: 100%;
    max-width: 480px;
    border-radius: 24px;
    padding: 48px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    position: relative;
    z-index: 1;
    animation: fadeInUp 0.6s ease-out;

    @keyframes fadeInUp {
      from {
        opacity: 0;
        transform: translateY(30px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
  }

  .form-header {
    text-align: center;
    margin-bottom: 40px;

    h2 {
      color: #2c3e50;
      font-size: 32px;
      margin-bottom: 12px;
      font-weight: 700;
      background: linear-gradient(135deg, #27ae60, #2ecc71);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }

    p {
      color: #7f8c8d;
      font-size: 16px;
      margin: 0;
    }
  }

  .floating-form {
    .input-group {
      position: relative;
      margin-bottom: 32px;

      input {
        width: 100%;
        padding: 16px 20px;
        border: 2px solid #e1e8ed;
        border-radius: 16px;
        font-size: 16px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        background: rgba(255, 255, 255, 0.9);
        color: #2c3e50;

        &:focus {
          outline: none;
          border-color: #27ae60;
          box-shadow: 0 0 0 4px rgba(39, 174, 96, 0.1);
          background: rgba(255, 255, 255, 1);
        }

        &:valid {
          border-color: #27ae60;
        }
      }

      label {
        position: absolute;
        left: 35px;
        top: 50%;
        transform: translateY(-50%);
        background: transparent;
        padding: 0 8px;
        color: #95a5a6;
        font-size: 18px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        pointer-events: none;
        z-index: 1;

        &.focused {
          transform: translateY(-50%) translateX(100px) rotate(15deg) scale(0.8);
          opacity: 0;
          animation: labelSlideOut 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55) forwards;
        }
      }

      // 移除下划线效果
      .highlight {
        display: none;
      }
    }

    .sms-input-group {
      input {
        padding-right: 120px;
      }

      .send-sms-btn {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        padding: 8px 16px;
        background: linear-gradient(135deg, #27ae60, #2ecc71);
        color: white;
        border: none;
        border-radius: 12px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
        min-width: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 4px;

        &:hover:not(:disabled) {
          transform: translateY(-50%) translateY(-1px);
          box-shadow: 0 4px 12px rgba(39, 174, 96, 0.3);
        }

        &:disabled {
          opacity: 0.6;
          cursor: not-allowed;
          transform: translateY(-50%);
        }

        &.loading {
          .loading-icon {
            animation: spin 1s linear infinite;
          }
        }
      }
    }
  }

  .button-group {
    display: flex;
    gap: 16px;
    margin-top: 24px;

    .submit-btn {
      flex: 3;
      padding: 16px 24px;
      background: linear-gradient(135deg, #27ae60, #2ecc71);
      color: white;
      border: none;
      border-radius: 16px;
      font-size: 18px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 12px;
      position: relative;
      overflow: hidden;

      &:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(39, 174, 96, 0.3);
      }

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none;
      }

      &.loading {
        .loading-icon {
          animation: spin 1s linear infinite;
        }
      }
    }

    .back-btn {
      flex: 1;
      background: transparent;
      border: 2px solid #e1e8ed;
      color: #7f8c8d;
      padding: 12px 20px;
      border-radius: 16px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: #27ae60;
        color: #27ae60;
        background: rgba(39, 174, 96, 0.05);
        transform: translateY(-1px);
      }
    }
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  @keyframes labelSlideOut {
    0% {
      transform: translateY(-50%) translateX(0) rotate(0deg) scale(1);
      opacity: 1;
    }
    100% {
      transform: translateY(-50%) translateX(100px) rotate(15deg) scale(0.8);
      opacity: 0;
    }
  }

  @keyframes labelSlideIn {
    0% {
      transform: translateY(-50%) translateX(100px) rotate(-15deg) scale(0.8);
      opacity: 0;
    }
    60% {
      transform: translateY(-50%) translateX(15px) rotate(8deg) scale(1.2);
      opacity: 0.8;
    }
    80% {
      transform: translateY(-50%) translateX(-8px) rotate(-3deg) scale(1.1);
      opacity: 0.9;
    }
    90% {
      transform: translateY(-50%) translateX(3px) rotate(1deg) scale(1.05);
      opacity: 0.95;
    }
    100% {
      transform: translateY(-50%) translateX(0) rotate(0deg) scale(1);
      opacity: 1;
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .modern-mobile-login-container {
      max-width: 400px;
      padding: 32px 24px;
    }

    .form-header h2 {
      font-size: 28px;
    }

    .sms-input-group {
      .send-sms-btn {
        min-width: 70px;
        padding: 6px 12px;
        font-size: 12px;
      }
    }

    .button-group {
      gap: 12px;

      .submit-btn {
        padding: 14px 20px;
        font-size: 16px;
      }

      .back-btn {
        padding: 10px 16px;
        font-size: 12px;
      }
    }
  }

  @media (max-width: 480px) {
    .modern-mobile-login-wrapper {
      padding: 16px;
    }

    .modern-mobile-login-container {
      padding: 24px 20px;
    }

    .form-header h2 {
      font-size: 24px;
    }

    .form-header p {
      font-size: 14px;
    }

    .floating-form .input-group input {
      padding: 14px 16px;
      font-size: 14px;
    }

    .button-group {
      gap: 8px;

      .submit-btn {
        padding: 12px 16px;
        font-size: 14px;
      }

      .back-btn {
        padding: 8px 12px;
        font-size: 12px;
      }
    }
  }

  // 深色模式支持
  @media (prefers-color-scheme: dark) {
    .modern-mobile-login-container {
      background: rgba(44, 62, 80, 0.95);
      border-color: rgba(255, 255, 255, 0.1);
    }

    .form-header h2 {
      color: #ecf0f1;
    }

    .form-header p {
      color: #bdc3c7;
    }

    .floating-form .input-group input {
      background: rgba(52, 73, 94, 0.9);
      border-color: #34495e;
      color: #ecf0f1;

      &:focus {
        background: rgba(52, 73, 94, 1);
      }
    }

    .floating-form .input-group label {
      color: #bdc3c7;
    }

    .button-group .back-btn {
      border-color: #34495e;
      color: #bdc3c7;

      &:hover {
        border-color: #27ae60;
        color: #27ae60;
        background: rgba(39, 174, 96, 0.1);
      }
    }
  }

  // 暗色模式下输入框样式
  .dark .modern-mobile-login-wrapper .input-group input,
  .dark .modern-mobile-login-wrapper .input-group input:focus {
    background: #23272f !important;
    color: #fff !important;
    border-color: #444a58 !important;
    box-shadow: none !important;
  }

  .dark .modern-mobile-login-wrapper .input-group input:focus {
    border-color: #27ae60 !important;
    box-shadow: 0 0 0 4px rgba(39, 174, 96, 0.15) !important;
  }
</style>
